import traceback

from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework.status import HTTP_500_INTERNAL_SERVER_ERROR, HTTP_200_OK

from programApi.rank.rank_models import RankModel
from programApi.rank.rank_serializers import RankSerializer

"""
    @url('/rank/')
"""


class RankViewSet(viewsets.ViewSet):

    def list(self, request):
        """
        排行榜功能的get方法
        @param request:
        @return:
        """
        queryset = RankModel.objects.all().order_by('-userRankElo')
        serializer = RankSerializer(queryset, many=True)
        return Response(serializer.data)

    def create(self, request):
        """
        排行榜功能的post方法，向排行榜Insert或者Update数据
        @param request:
        @return:
        """
        user_avatar_url = request.data.get('userAvatarUrl')
        user_nick_name = request.data.get('userNickName')
        user_id = request.data.get('userId')
        score = request.data.get('score')
        try:
            if RankModel.objects.filter(userAvatarUrl=user_avatar_url, userId=user_id, userName=user_nick_name):
                rank_object = (
                    RankModel.objects.get(userAvatarUrl=user_avatar_url, userId=user_id, userName=user_nick_name))
                rank_object.userRankElo += score
                rank_object.save()
                return Response(status=HTTP_200_OK)
            else:
                data = {'userId': user_id, 'userName': user_nick_name, 'userAvatarUrl': user_avatar_url,
                        'userRankElo': score}
                serializer = RankSerializer(data=data)
                if serializer.is_valid():
                    serializer.save()
                return Response(status=HTTP_200_OK)
        except Exception as e:
            traceback.print_exc()
        return Response(status=HTTP_500_INTERNAL_SERVER_ERROR)
